const puppeteer = require("puppeteer");
const utils = require("./utils.js");

//本机Chrome浏览器的绝对路径
// const chrome = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
//mac系统,hosts文件路径/etc/hosts，浏览器输入chrome://version/查看安装路径
const chrome = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";

const url1 = "https://github.com.ipaddress.com/";
const url2 = "https://fastly.net.ipaddress.com/github.global.ssl.fastly.net";
const url3 = "https://github.com.ipaddress.com/assets-cdn.github.com";

start();

async function start() {
  utils.print("解析开始...");
  try {
    const { browser, page } = await init();
    let list = [];

    let address1 = await getAddress(page, url1);
    list.push(address1 + " github.com");
    utils.print("1.获取ip成功", "warn");

    utils.sleep(200);

    let address2 = await getAddress(page, url2);
    list.push(address2 + " github.global.ssl.fastly.net");
    utils.print("2.获取ip成功", "warn");

    utils.sleep(200);

    let ips = await getAssets(page, url3);
    ips.forEach((element) => {
      list.push(element + " assets-cdn.github.com");
    });
    utils.print("3.获取ip成功", "warn");

    utils.sleep(200);

    browser.close();
    utils.print("解析成功,把下面内容添加到hosts文件", "success");
    console.log(list.join("\n\r"));
  } catch (e) {
    utils.print(e, "warn");
  }
}

async function init() {
  const browser = await puppeteer.launch({
    args: ["--no-sandbox"], //传递给chrome实例的其他参数，比如你可以使用”–ash-host-window-bounds=1024x768” 来设置浏览器窗口大小
    dumpio: false,
    executablePath: chrome, //Chrome浏览器的绝对路径
    headless: true, //是否运行在浏览器headless模式，true为不打开浏览器执行，默认为true
  });
  const page = await browser.newPage();
  return { browser, page };
}

async function getAddress(page, url) {
  //等待页面加载完毕
  await page.goto(url, { waitUntil: "networkidle2" });

  //等待元素加载完成
  await page.waitForSelector(".comma-separated");

  //执行js获取对应数据
  const result = await page.evaluate(() => {
    var ip = document.querySelector(".comma-separated").textContent;
    return ip;
  });
  return result;
}

async function getAssets(page, url) {
  //等待页面加载完毕
  await page.goto(url, { waitUntil: "networkidle2" });

  //等待元素加载完成
  await page.waitForSelector(".table-border-row.table-v.panel-item.faq ul");

  //执行js获取对应数据
  const result = await page.evaluate(() => {
    var t = [...document.querySelectorAll(".table-border-row.table-v.panel-item.faq ul li")];
    return t.map((i) => i.innerText);
  });
  return result;
}
